﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using Common;
using ViewModel;

namespace Controllers.Filter
{
    /// <summary>
    ///异常过滤器（当前层次的异常过滤,只能处理500的异常，一般用于Controller）
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class ExceptionAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            #region 跳转异常页面前先记录异常

            Exception ex = filterContext.Exception;
            Type exceptionType = typeof(Exception);

            if (ex.GetType() == exceptionType)//异常可能被Throw new Exception(e.Message);处理过
            {
                LogHelper.WriteErrorLog(exceptionType, ex, "异常可能被程序捕获处理(*^__^*)");
            }
            else
            {
                LogHelper.WriteErrorLog(ex.GetType(), ex, "异常未被程序捕获处理(●￣(ｴ)￣●)");
            }

            #endregion

            #region 非ajax异常页面由customErrors配置项控制跳转。（ajax异常直接在此处理掉，由页面的ajax输出异常，不再上抛。）

            if (filterContext.ExceptionHandled == false)//未处理异常
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult()
                    {
                        ContentEncoding = Encoding.UTF8,
                        Data = new ResultModel
                        {
                            Pass = false,
                            Msg = "ServerError"
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }

                filterContext.ExceptionHandled = true;
            }

            #endregion

        }
    }

}
